import { useEffect, useState, useRef } from "react"

export const useCallbackState = <T>(
  data: T
): [T, (res: T, callback?: (state: T) => void) => void] => {
  const [state, setState] = useState<T>(data)
  const callbackRef = useRef((state: T) => {})
  useEffect(() => {
    if (typeof callbackRef.current == "function") {
      callbackRef.current(state)
    }
  }, [state])

  return [
    state,
    (res: T, callback?: (state: T) => void) => {
      callbackRef.current = callback as (state: T) => void
      setState(res)
    },
  ]
}
